package com.wechat.wechat.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 设置和获取cookie工具类
 * @author NN
 * @2020/2/28 20:59
 */
public class CookieUtil {

    /**
     * 往response中增加cookie对象
     */
    public static void set(HttpServletResponse response,
                           String name,
                           String value,
                           int maxAge)
    {
        Cookie cookie=new Cookie(name,value);
        cookie.setPath("/");
        cookie.setMaxAge(maxAge);//过期时间
        response.addCookie(cookie);
    }

    /**
     * 根据cookie的名字获取request中cookie的值
     */
    public static Cookie get(HttpServletRequest request,
                             String name)
    {
        Map<String,Cookie> cookieMap=readCookieMap(request);
        if(cookieMap.containsKey(name))
        {
            return cookieMap.get(name);
        }else
        {
            return null;
        }
    }

    private static Map<String,Cookie> readCookieMap(HttpServletRequest request)
    {
        Cookie[] cookies=request.getCookies();
        Map<String,Cookie> cookieMap=new HashMap<>();
        if(cookies!=null)
        {
            for(Cookie cookie:cookies)
            {
                cookieMap.put(cookie.getName(),cookie);
            }
        }
        return cookieMap;
    }
}
